using System;
using System.Linq;
using HengTong.Model.Db;
using HengTong.Model.Db.System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WalkingTec.Mvvm.Core.Extensions;

namespace HengTong.ViewModel._Admin.SysUserJobPositionVms;

public partial class SysUserJobPositionBatchVm
{
    
    public override bool DoBatchDelete()
    {
        var scope = Wtm.ServiceProvider.CreateScope();
        var logger = scope.ServiceProvider.GetRequiredService<ILogger<SysUserJobPositionBatchVm>>();
        logger.LogInformation("删除岗位, {@ids}, {@user}", Ids, Wtm.LoginUserInfo?.ITCode);
        var transaction = Wtm.DC.BeginTransaction();
        try
        {
            var ids = this.Ids.Select(Guid.Parse).ToList();
            var list = Wtm.DC.Set<SysUserJobPosition>()
                .Where(e => ids.Contains(e.ID))
                .ToList();
            DC.Set<SysUserJobPosition>().RemoveRange(list);
            DC.SaveChanges();
            var userIds = list.Select(e => e.UserId).Distinct().ToList();
            var vm = new SysUserJobPositionVm
            {
                DC = DC,
                Wtm = Wtm
            };
            foreach (var id in userIds)
            {
                if(id == null) continue;
                vm.UpdateUserGroupAsync(id.Value).Wait();
            }
            transaction.Commit();
            return true;
        }
        catch (Exception e)
        {

            logger.LogError(e, $"批量删除岗位发生异常, {e.Message}");
            MSD.AddModelError(" ", $"批量删除操作异常: {e.Message}");
            transaction.Rollback();
            return false;
        }
        finally
        {
            transaction.Dispose();
        }
    }
}